import os

from celery_task.celery_init import celery
from insects_detection.insects_utils import insects_tools
from insects_detection.pic_utils import pic_tools
import json

from utils.redis_utils import RedisTool


@celery.task(bind=True, name="celery_task.update_insects_task")
def recompute_insects_distribution(self, gallery_path, processed_gallery_path, chas_data_path, model_path):
    store_folder_path = pic_tools.write_all_processed_imgs(gallery_path, processed_gallery_path, True, self)
    pic_tools.rename_imgs(store_folder_path, '1', '.jpg')
    pic_tools.extract_all_imgs_characteristcs(store_folder_path, chas_data_path, True, self)
    scaler_path = 'F:\python project\Code warehouse\insects_detection_flask_backend2\insects_detection\trainning_models\Model4April_scaler.pkl'
    folder_name = store_folder_path.rsplit(os.sep, 1)[1]
    insects_chas_path = chas_data_path + os.sep + folder_name
    detailed_insects_info = insects_tools.classify_green_house_insects(insects_chas_path, model_path, scaler_path)
    # detailed_insects_info_json = json.dumps(detailed_insects_info, ensure_ascii=False)
    # redis写入相关操作
    r = RedisTool(host='39.102.44.159', port=6379, db=0, password='inetlabredis')
    info_key = 'insects:'+folder_name+':test'
    r.update(info_key, detailed_insects_info)
    self.update_state(state='ALL_COMPLETE',
                      meta={'current': 100, 'total': 100,
                            'status': "Succeed in updating insects info!",
                            'result': detailed_insects_info
                            })
    return {'current': 100, 'total': 100, 'status': 'Task completed!',
            'result': detailed_insects_info}
